﻿using System;
using System.Configuration;
using System.IO;
using System.Web;

namespace Shuba.Web.master
{
    public partial class holiday_upload : basePage
    {
        string msg = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_HOLIDAY");

                if (!IsUserAdd(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("MSTR_HOLIDAY");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Boolean fileOK = false;
                string path = Server.MapPath("~/uploads/");
                string ErrMessage = "";
                int ErrLine = 0;

                if (FileUpload1.HasFile)
                {
                    String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedExtensions = { ".txt", ".csv" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }

                if (fileOK)
                {
                    status.Visible = true;
                    string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(fName);

                    var filestream = File.OpenText(fName);
                    string contents = filestream.ReadToEnd();
                    filestream.Close();

                    var bl = new Business.Holiday();
                    Model.HolidayInfo Info;

                    char rowDelimiter = '\n';
                    char fldDelimiter = '\t';
                    var rows = contents.Split(rowDelimiter);

                    for (var i = 1; i < rows.Length - 1; i++)
                    {
                        var fields = rows[i].Split(fldDelimiter);

                        if (fields.Length > 1)
                        {
                            if (!IsValidEntryFormat(fields[0].Trim(), "D")) ErrMessage += "<BR> Invalid Holiday Date Value or Format at Line :" + i.ToString();                            

                            if (ErrMessage == "")
                            {
                                Info = new Shuba.Model.HolidayInfo();

                                try
                                {
                                    Info.HOLIDAY_DATE = Convert.ToDateTime(fields[0].Trim());
                                    Info.HOLIDAY_NAME = fields[1].Trim().Replace("'", "`").Replace("\"", "");
                                    Info.ACT_TYPE = "UPLOAD";
                                    Info.IS_ACTIVE = "1";
                                    Info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                                    Info.ENTRY_DATE = ProcessingDate();
                                    Info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                                    Info.UPDATE_DATE = ProcessingDate();
                                    Info.HOLIDAY_DATE_ORIG = Convert.ToDateTime(fields[0].Trim());

                                    bl.Save(Info);
                                }
                                catch (Exception ex)
                                {
                                    ErrMessage += this.GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                                    lblStatus.Text = ErrMessage + "<br>" + ex.Message;
                                }
                            }
                            else
                            {
                                ErrLine = i;
                                i = rows.Length;
                            }
                        }
                    }
                    File.Delete(fName);
                    AddLog("UPLOAD", "UPLOAD HOLIDAY");

                    if (ErrMessage == "")
                    {
                        msg = this.GetGlobalResourceObject("Messages", "UploadSuccessAlert").ToString();
                        lblStatus.Text = msg;
                        FileUpLoadValidator.Visible = false;
                        AlertAndRedirect(msg, "holiday_list.aspx");
                    }
                    else
                    {
                        lblStatus.Text = "<b>Error Found:</b>" + ErrMessage + "<br><br><b>Upload Process Stoped at Line: " + ErrLine + "</b>";
                        FileUpLoadValidator.Visible = false;
                    }
                }
                else
                {
                    msg = this.GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString();
                    lblStatus.Text = msg;
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("holiday_list.aspx");
        }
    }
}
